package com.csk.zsk.compents.action;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.csk.zsk.commons.action.AjaxActionSupport;
import com.csk.zsk.commons.utils.encode.JsonBinder;
import com.csk.zsk.commons.utils.web.struts2.Struts2Utils;
import com.csk.zsk.compents.entity.Note;
import com.csk.zsk.compents.entity.User;
import com.csk.zsk.compents.service.NoteService;
import com.csk.zsk.compents.utils.Constants;

@Controller
@Scope("prototype")
public class NoteAction extends AjaxActionSupport {

	private static final long serialVersionUID = 2175847091406999231L;
	private static JsonBinder binder = JsonBinder.buildNonDefaultBinder();

	@Autowired
	private NoteService noteService;

	public void getNoteByUserId() {
		User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION);
		if (user == null) {
			user = new User();
			user.setId("1");
		}
		List<Note> noteList = noteService.getNoteByUserId(user.getId());
		String json = binder.toJson(noteList);
		Struts2Utils.renderJson(json);
	}

	public void saveNote() {
		String id = Struts2Utils.getParameter("id");
		String content = Struts2Utils.getParameter("content");
		String color = Struts2Utils.getParameter("color");
		String zIndex = Struts2Utils.getParameter("zIndex");
		User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION);
		if (user == null) {
			user = new User();
			user.setId("1");
		}
		Note note = null;
		if (id != null && !"".equals(id)) {
			note = noteService.getNoteById(id);
		} else {
			note = new Note();
		}
		note.setContent(content);
		note.setColor(color);
		note.setzIndex(Integer.parseInt(zIndex));
		note.setUser(new User());
		note.getUser().setId(user.getId());
		noteService.saveNote(note);
		String json = binder.toJson(note);
		Struts2Utils.renderJson(json);
	}

	public void updateNote() {
		String xPos = Struts2Utils.getParameter("xPos");
		String yPos = Struts2Utils.getParameter("yPos");
		String zIndex = Struts2Utils.getParameter("zIndex");
		String id = Struts2Utils.getParameter("id");
		Note note = noteService.getNoteById(id);
		note.setxPos(Integer.parseInt(xPos));
		note.setyPos(Integer.parseInt(yPos));
		note.setzIndex(Integer.parseInt(zIndex));
		noteService.saveNote(note);
	}

	public void deleteNote() {
		String id = Struts2Utils.getParameter("id");
		noteService.deleteNote(id);
	}

}
